package com.lh.interceptor;
import com.lh.utils.JwtUtil;
import com.lh.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //        校验逻辑实现
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
//            将用户数据存到ThreadLocal中
            ThreadLocalUtil.set(map);
//            拦截token和redis中的token进行对比，相同放行，不同拦截
            String s = stringRedisTemplate.opsForValue().get(token);
            if (s == null) {
             throw new RuntimeException();//redis中没有token则抛异常
            }

        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        请求结束之后关闭线程，防止内存溢出
        ThreadLocalUtil.remove();
    }
}
